/*
 * @Description:
 * @Author: fhw
 * @Date: 2023-03-26 15:05:23
 */
import { Injectable, UseFilters } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { InjectRepository } from '@nestjs/typeorm';
import { isNil } from 'ramda';
import { TokenDto } from 'src/common/auth/constants';
import { IdDto } from 'src/common/dto/dto';
import { HttpExceptionFilter } from 'src/common/http-exception.filter';
import { getPagination, throwHttp } from 'src/utlis';
import { isTrue } from 'src/utlis/tools';
import { Repository, Between } from 'typeorm';
import {
  GetCategoryDto,
  CreateCategoryDto,
  UpdateCategoryDto,
} from './dto/category.dto';
import { CategoryEntity } from './entities/category.entity';

@Injectable()
export class CategoryService {
  constructor(
    @InjectRepository(CategoryEntity)
    private categoryEntityRepository: Repository<CategoryEntity>,
    private readonly jwtService: JwtService,
  ) { }
  async getCategory(params: GetCategoryDto) {
    try {
      const {
        name,
        status,
        sort,
        createTimeStart,
        createTimeEnd,
      } = params;
      const where: GetCategoryDto = {
        name,
        status,
        sort,
      };
      // 创建时间筛选
      if (!isNil(createTimeStart) && !isNil(createTimeEnd)) {
        where.createDate = Between(createTimeStart, createTimeEnd);
      }
      // 分页
      const { pageSize, pageNum } = getPagination({
        pageSize: params.pageSize,
        pageNum: params.pageNum,
      });
      const [data, total] = await this.categoryEntityRepository.findAndCount({
        where: {
          ...where,
        },
        cache: true,
        order: { createDate: 'DESC', sort: 'ASC' },
        skip: pageNum * pageSize,
        take: pageSize,
      });
      return {
        data,
        total,
        pageSize,
        pageNum: pageNum + 1,
      };
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 创建分类 */
  @UseFilters(new HttpExceptionFilter())
  async createCategory(body: CreateCategoryDto, operatorBy: TokenDto) {
    try {
      const { name, status, sort, lang } = body;
      const category = new CategoryEntity();
      category.name = name;
      category.status = status;
      category.sort = sort;
      category.lang = lang;
      category.createById = operatorBy.userId;
      const result = await this.categoryEntityRepository.manager.save(category);
      if (isTrue(result)) {
        return '问题反馈成功';
      }
      return '问题反馈失败';
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 更新分类 */
  @UseFilters(new HttpExceptionFilter())
  async updateCategory(body: UpdateCategoryDto, operatorBy: TokenDto) {
    try {
      const { name, sort, status, id, lang } = body;
      const categoryInfo = await this.getCategoryInfo({
        id,
      });
      if (!isTrue(categoryInfo)) {
        throwHttp('分类不存在');
        return;
      }
      const { affected } = await this.categoryEntityRepository
        .createQueryBuilder()
        .update(CategoryEntity)
        .set({
          name,
          sort, lang,
          status,
          updateById: operatorBy.userId,
        })
        .where('id = :id', { id })
        .execute();
      if (affected) {
        return '更新成功';
      }
      throwHttp('更新失败');
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 获取分类详情 */
  @UseFilters(new HttpExceptionFilter())
  async getCategoryInfo(where) {
    try {
      return await this.categoryEntityRepository.findOne({
        where,
        cache: true,
      });
    } catch (error) {
      throwHttp(error.message);
    }
  }
  /** 删除分类 */
  @UseFilters(new HttpExceptionFilter())
  async deleteCategory({ id }: IdDto) {
    try {
      const data = await this.getCategoryInfo({ id });
      if (!isTrue(data)) {
        throwHttp('分类不存在');
        return;
      }
      await this.categoryEntityRepository.softDelete(id);
      return '删除成功';
    } catch (error) {
      throwHttp(error.message);
    }
  }
}
